#include <stdio.h>
#include <stdlib.h>

#define ERAWRIM_PATH "~/.erawrim/"

enum {EMPTY = 0x000, READERUP = 0x401, READERDOWN = 0x501, INSTALLATION = 0x102, REMOVED = 0x202};

int main(int argc, char *argv[])
{
  char* detected_device;
  
  FILE *fh;
  short int empty;
  short unsigned int state;
  long unsigned int tag;
  
  char control[50]; 
  
  if(!argc==2){
    return EXIT_FAILURE;
  }
  
  detected_device=argv[1];
  
  fh = fopen(detected_device,"rb");
  if(fh == NULL) {
    printf("Error while opening: %s\n", detected_device);
    return EXIT_FAILURE;
  }
  else
  {
    printf("Successfully opened: %s\n", detected_device);
    while(1)
    {
      fread(&state, sizeof(short int),1, fh); 
      
      if(state != EMPTY)
      {
	fread(&empty, sizeof(short unsigned int),1, fh); 
	fread(&tag, sizeof(long unsigned int),1, fh); 
	fread(&empty, sizeof(short unsigned int),1, fh); 
	
	switch(state)
	{
	  case READERUP:
//	    printf("The mir:ror has just been connected.\n");
	    system("erawrim_do readerup");
	    break;
	  case READERDOWN:
//	    printf("The mir:ror has been turned upside down.\n");
	    system("erawrim_do readerdown");
	    break;
	  case INSTALLATION:
//	    printf("%ld been connected.\n",tag);
	    sprintf(control, "erawrim_do conected %ld",tag);
	    system(control);
	    //system("./erawrim_do.sh conected");
	    break;
	  case REMOVED:
//	    printf("%ld vient de partir.\n",tag);
	    sprintf(control, "erawrim_do removed %ld",tag);
	    system(control);
	    //system("./erawrim_do.sh removed");
	    break;
	  default:
	    break;
	}
	
      }
    }
  }
  
  fclose(fh);
  return EXIT_SUCCESS;
}

